/**
 * Created by Administrator on 2017/4/5 0005.
 */
import React from "react";
import {Modal, message} from 'antd';
import GetQiNiuTokenMutation from "../mutation/GetQiNiuTokenMutation"
import Relay from "react-relay";
import SaveImageMutation from "../mutation/SaveImageMutation"
import ReactKey from "../../../util/ReactKey"
import Config from "../../../util/Config"

export default class CalendarModal extends React.Component{
    constructor(props){
        super(props);
        this.state={
            visible:false,
            imageUrl:'',
            index:''
        }
        this.file =''
        this.imageUrl = ''
    }

    componentWillMount(){

    }

    closemodal(){
        this.setState({imageUrl:'',visible:false});
    }

    uploadfile(url,index){
        if (!this.state.imageUrl) {
            message.config({
                top: 30,
            })
            message.info('请选择图片');
            return;
        }
        this.props.setgoodsimg(url,index);
    }

    chosefile(){
        if(document.getElementById('choiceImageupdata'+this.state.index).files[0]){
            this.file = document.getElementById('choiceImageupdata'+this.state.index).files[0];
        }
        this.upload();
    }

    upLoadFile(file, token) {
        let upLoadUrl = "http://up-z2.qiniu.com";
        let xhr = new XMLHttpRequest();
        xhr.open("POST", upLoadUrl, true);
        let timestamp = Date.parse(new Date());
        let fileKey = timestamp+this.file.name;
        let formData = new FormData();
        formData.append('file', file);
        formData.append('token', token);
        formData.append('key',fileKey);
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    let res = JSON.parse(xhr.responseText);
                    Relay.Store.commitUpdate(
                        new SaveImageMutation({
                            realName:this.file.name,
                            token:res.hash,
                            url:Config.qiuniu+res.key
                        }),
                        {
                            onFailure: () => {

                            },
                            onSuccess: (response) => {
                                let errorCode = response.saveImage.saveImage.errorCode;
                                if(errorCode ==0){
                                    // let realName = response.saveImage.saveImage.imageStorge.realName;
                                    let imageUrl = response.saveImage.saveImage.imageStorge.imageUrl;
                                    this.imageUrl = imageUrl;
                                    this.setState({
                                        imageUrl:imageUrl
                                    });
                                }
                            }
                        }
                    )
                } else {
                    message.info('请求失败')
                }
            }
        };
        xhr.send(formData);
    }

    upload(){
        Relay.Store.commitUpdate(
            new GetQiNiuTokenMutation({}), {
                onSuccess: (res) => {
                    // console.warn(res);
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken
                        this.token = qiniutoken;
                        this.upLoadFile(this.file,qiniutoken)
                    }
                }
            }
        )
    }

    render(){
        return (
            <Modal
                visible={this.state.visible}
                onOk={this.uploadfile.bind(this,this.imageUrl,this.state.index)}
                onCancel={this.closemodal.bind(this)}
                maskClosable={false}
                title="添加图片"
                okText="确认"
                cancelText="取消"
                className="batchhint_modal order_frorm_addimgmodal"
            >
                <div className="order_frorm_addimgmodal_div">
                    <div>
                        <input ref={'upfile'} type="file" style={{position:"absolute",height:206,width:314,opacity:0
                                                                   ,marginLeft:73}} id={"choiceImageupdata"+this.state.index} onChange={this.chosefile.bind(this)} key={ReactKey.key}/>
                        <img className="order_frorm_addimgmodal_img" alt="+添加图片" src={this.state.imageUrl} />

                    </div>


                   {/* <button className="order_updata_addimgmodal_buttonup" onClick={this.uploadfile.bind(this,this.imageUrl,this.state.index)}>
                        确认</button>
                    <button className="order_updata_addimgmodal_buttoncn" onClick={this.closemodal.bind(this)}>取消</button>*/}
                </div>
            </Modal>
        )
    }
}
